package com.da.javatest.thread.juc.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author JokerDa.
 * @date 2021/7/7 16:06
 * Description:
 */
public class ThreadDemo3 {
    private int flag = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition c1 = lock.newCondition();
    private final Condition c2 = lock.newCondition();
    private final Condition c3 = lock.newCondition();

    public void printA(int loop) throws InterruptedException {
        try {
            lock.lock();
            while (flag != 1) {
                c1.await();
            }

            System.out.print("第" + loop + "轮 " + Thread.currentThread().getName() + "::");
            for (int i = 0; i < 5; i++) {
                System.out.print("A");
            }
            System.out.println();

            flag = 2;
            c2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printB(int loop) throws InterruptedException {
        try {
            lock.lock();
            while (flag != 2) {
                c2.await();
            }

            System.out.print("第" + loop + "轮 " + Thread.currentThread().getName() + "::");
            for (int i = 0; i < 7; i++) {
                System.out.print("B");
            }
            System.out.println();

            flag = 3;
            c3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printC(int loop) throws InterruptedException {
        try {
            lock.lock();
            while (flag != 3) {
                c3.await();
            }

            System.out.print("第" + loop + "轮 " + Thread.currentThread().getName() + "::");
            for (int i = 0; i < 9; i++) {
                System.out.print("C");
            }
            System.out.println();

            flag = 1;
            c1.signal();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ThreadDemo3 demo3 = new ThreadDemo3();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    demo3.printA(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A线程").start();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    demo3.printB(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B线程").start();

        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    demo3.printC(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C线程").start();
    }
}
